package cn.mcmarket.yhstick;

import net.milkbowl.vault.economy.Economy;
import org.bstats.bukkit.Metrics;
import org.bukkit.Material;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.plugin.RegisteredServiceProvider;
import org.bukkit.plugin.java.JavaPlugin;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public final class Yhstick extends JavaPlugin {
    private static Economy econ = null;
    private static Yhstick instance;
    private HashMap<String,Double> goods;

    public static Yhstick getInstance() {
        return instance;
    }

    public static Economy getEconomy() {
        return econ;
    }


    @Override
    public void onEnable() {
        // Plugin startup logic
        int pluginId = 14896; // <-- Replace with the id of your plugin!
        Metrics metrics = new Metrics(this, pluginId);
        instance = this;
        goods = new HashMap<>();
        if (!setupEconomy()) {
            log2Console(String.format("c[%s] - 未找到经济插件，将关闭此插件!", getDescription().getName()));
            getServer().getPluginManager().disablePlugin(this);
            return;
        }
        loadCfg();
        initCfg();
        getServer().getPluginManager().registerEvents(new PlayerListener(), this);
    }

    private void initCfg() {
        for (String item : getConfig().getConfigurationSection("items").getKeys(false)) {
            goods.put(item,getConfig().getDouble("items."+item));
        }
    }

    private boolean setupEconomy() {
        if (getServer().getPluginManager().getPlugin("Vault") == null) {
            return false;
        }
        RegisteredServiceProvider<Economy> rsp = getServer().getServicesManager().getRegistration(Economy.class);
        if (rsp == null) {
            return false;
        }
        econ = rsp.getProvider();
        return econ != null;
    }

    private void loadCfg() {
        File f = new File(getDataFolder() + "/config.yml");
        if (f.exists()) {
            log2Console("a检测到配置文件，即将加载!");
        } else {
            log2Console("c未检测到配置文件，生成默认配置中!");
            saveDefaultConfig();
        }
        reloadConfig();
        log2Console("a插件加载完成");
    }

    @Override
    public void onDisable() {
        // Plugin shutdown logic
    }

    public void log2Console(String message) {
        getServer().getConsoleSender().sendMessage("§" + message);

    }

    public boolean isStick(ItemStack item) {
        if (!item.hasItemMeta()) return false;
        if (!item.getItemMeta().hasDisplayName()) return false;
//        System.out.println(item.getItemMeta().getDisplayName());
//        System.out.println(getConfig().getString("stickName"));
        return item.getItemMeta().getDisplayName().startsWith(getConfig().getString("stickName"));
    }

    @Override
    public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
        if (sender instanceof ConsoleCommandSender || sender.isOp()) {
            //yhs give stick player_name
            if (args.length == 3 && args[0].equals("give")) {
                String stickName = args[1];
                String playerName = args[2];
                Player p = getServer().getPlayerExact(playerName);
                if (p != null && p.isOnline()) {
                    if (giveItem2Player(stickName, p)) {
                        sender.sendMessage("§a成功发送物品!");
                    } else {
                        sender.sendMessage("§c魔棒不存在或输入错误.");
                    }
                } else {
                    sender.sendMessage("§c该玩家不存在或不在线.");
                }
            }
            else if (args.length==1&& args[0].equals("reload")){
                reloadConfig();
                initCfg();
                sender.sendMessage("§a重载成功!");
            }

        }
        return false;
    }

    private boolean giveItem2Player(String stickName, Player p) {
        if (!getConfig().getConfigurationSection("sticks").getKeys(false).contains(stickName)) return false;
        ItemStack is = new ItemStack(Material.valueOf(getConfig().getString("sticks." + stickName + ".type")));
        ItemMeta itemMeta = is.getItemMeta();
        itemMeta.setDisplayName(getConfig().getString("sticks." + stickName + ".display"));
        List<String> stringList = getConfig().getStringList("sticks." + stickName + ".lore");
        stringList.add(antiStackTag());
        itemMeta.setLore(stringList);
        is.setItemMeta(itemMeta);
        p.getInventory().addItem(is);
        return true;
    }

    private String antiStackTag() {
        long l = System.currentTimeMillis();
        String a = (l + "").substring(3, 12);
        StringBuilder b = new StringBuilder();
        for (int i = 0; i < a.length();++i){
            String c = a.substring(i,i+1);
            b.append("§").append(c);
        }
        return b.toString();
    }

    public boolean isGoods(String type) {
        return goods.containsKey(type);
    }

    public double sellItem(ItemStack itemStack) {
        double price = goods.get(itemStack.getType().name())*itemStack.getAmount();
        itemStack.setAmount(0);
        return price;
    }

    public void sellItems(Inventory blockInventory, Player player,ItemStack is) {
        double price = 0;
        for (ItemStack itemStack : blockInventory) {
            if (itemStack==null)continue;
            String type = itemStack.getType().name();
            if (isGoods(type)){
                double prices = sellItem(itemStack);
                price +=prices;
            }
        }
        if (price > 0){
            UseOneTimes(is);
            econ.depositPlayer(player,price);
            String string = getConfig().getString("lang.sell");
            player.sendMessage(string.replace("{0}",price+""));
        }
    }

    private void UseOneTimes(ItemStack is) {
        if (isStick(is)){
            ItemMeta itemMeta = is.getItemMeta();
            List<String> lore = itemMeta.getLore();
            List<String> newlore = new ArrayList<>();
            for (String line:lore){
                String timePrefix = getConfig().getString("timePrefix");
                if (line.contains(timePrefix)){
                    int num = Integer.parseInt(line.split(timePrefix)[1]);
                    newlore.add(timePrefix +(num-1));
                    if (num-1<=0){
                        is.setAmount(0);
                        return;
                    }
                }else{
                    newlore.add(line);
                }
            }
            itemMeta.setLore(newlore);
            is.setItemMeta(itemMeta);

        }
    }
}
